package com.sunlands.zlcx.usercenter.service.status;

import com.sunlands.zlcx.usercenter.constant.LearningStatus;
import com.sunlands.zlcx.usercenter.constant.RedisKeyConst;
import com.sunlands.zlcx.usercenter.constant.YN;
import com.sunlands.zlcx.usercenter.domain.UsersLearnTimingDO;
import com.sunlands.zlcx.usercenter.domain.UsersTargetRelationDO;
import com.sunlands.zlcx.usercenter.exception.CheckParamException;
import com.sunlands.zlcx.usercenter.service.status.common.AbstractStudyStatus;
import com.sunlands.zlcx.usercenter.util.BeanPropertiesUtil;
import com.sunlands.zlcx.usercenter.util.CalendarUtil;
import com.sunlands.zlcx.usercenter.vo.UserMonthLearnVO;
import com.sunlands.zlcx.usercenter.vo.UsersStudyInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author gaoyanfeng
 * @create 2019-04-28 9:50
 **/
@Component
@Slf4j
public class TimeLearnRoomStartLearn extends AbstractStudyStatus implements BeanPropertiesUtil {

    @Override
    public void handle(UsersStudyInfoVO usersStudyInfoVO, UsersTargetRelationDO usersTargetRelationDO) {
        Long userId = usersTargetRelationDO.getUserId();
        if (null == usersStudyInfoVO.getLianMaiId()) {
            throw new CheckParamException("连麦id参数不合法");
        }

        checkTimingPeriod(usersStudyInfoVO, userId);
        redisTemplate.opsForValue().set(RedisKeyConst.getStudyName(userId), usersStudyInfoVO.getStudyInfoName());

        Date startTime = new Date();
        usersService.updateStatus(userId, LearningStatus.TIME_LEARN_ROOM.getCode(), startTime, usersStudyInfoVO.getRoomId(), usersStudyInfoVO.getLianMaiId());

        Date countTime = CalendarUtil.getDateHoursBefore(startTime, 3);
        UsersLearnTimingDO usersLearnTimingDO = UsersLearnTimingDO
                .builder()
                .contentId(usersStudyInfoVO.getContentId())
                .status(YN.NO.getCode())
                .learnName(usersStudyInfoVO.getStudyInfoName())
                .targetId(usersTargetRelationDO.getTargetId())
                .countTime(countTime)
                .week(CalendarUtil.getWeek(countTime))
                .startTime(startTime)
                .type(UsersLearnTimingDO.TypeEnums.TIME_LEARN_ROOM.code)
                .endTime(usersStudyInfoVO.getEndTime())
                .userId(usersStudyInfoVO.getUserId())
                .contentId(usersStudyInfoVO.getContentId())
                .build();

        UserMonthLearnVO.FriendLearnInfo learnInfo = usersStudyService.getLearnRankList(userId, 0)
                .stream()
                .filter(friendLearnInfo -> friendLearnInfo.getFriendId().equals(userId))
                .findFirst()
                .orElse(null);
        log.debug("FriendLearnInfo = {} ", learnInfo);
        usersLearnTimingDO.setStartSort(Objects.nonNull(learnInfo) ? learnInfo.getIndex() : 1);
        usersLearnTimingRepository.save(usersLearnTimingDO);

    }
}
